#include "tcpserver.h"

TcpServer::TcpServer(QObject *parent)
    : QObject(parent), server(new QTcpServer(this))
{
    // 连接新连接信号到槽
    connect(server, &QTcpServer::newConnection, this, &TcpServer::newConnection);
}

TcpServer::~TcpServer() {
    server->close();
    delete server;
}

bool TcpServer::startServer(quint16 port) {//监听本地端口port
    if (!server->listen(QHostAddress::Any, port)) {
        qDebug() << "Server could not start:" << server->errorString();
        return false;
    }
    qDebug() << "Server started on port:" << port;
    return true;
}

void TcpServer::newConnection() {
    QTcpSocket *clientSocket = server->nextPendingConnection();
    if (clientSocket) { // 添加空指针检查
        connect(clientSocket, &QTcpSocket::readyRead, this, &TcpServer::onReadyRead);

        connect(clientSocket, &QTcpSocket::disconnected, this, &TcpServer::onDisconnected);

        qDebug() << "New connection from:" << clientSocket->peerAddress().toString();
    } else {
        qDebug() << "Unexpected null client socket in newConnection";
    }
}

void TcpServer::onReadyRead() {
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
    if (clientSocket) {
        QByteArray data = clientSocket->readAll();
        qDebug() << "Received data:" << data;
        // 在这里处理接收到的数据
        // ...
    }
}

void TcpServer::onDisconnected() {
    QTcpSocket *clientSocket = qobject_cast<QTcpSocket *>(sender());
    if (clientSocket) {
        qDebug() << "Client disconnected:" << clientSocket->peerAddress().toString();
        clientSocket->deleteLater(); // 清理socket对象
    }
}
